package com.bitrate.dagger.common.maker;

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

public class GsonMaker {

	private volatile static Gson builder = null;

	/**
	 * 单例模式，双检查锁模式，在并发环境下对象只被初始化一次
	 */
	public static Gson getInstance() {
		if (builder == null) {
			synchronized (Gson.class) {
				builder = new GsonBuilder()
						.serializeNulls()
						.disableInnerClassSerialization()
						.disableHtmlEscaping()
						.setPrettyPrinting()
						.registerTypeAdapter(String.class, STRING)
						.registerTypeAdapter(Integer.class, INTEGER).create();
			}
		}
		return builder;
	}

	// 自定义String适配器
	private static final TypeAdapter<?> STRING = new TypeAdapter() {
		@Override
		public void write(JsonWriter jsonWriter, Object o) throws IOException {
			if (o == null) {
				// 在这里处理null改为空字符串
				jsonWriter.value("");
				return;
			}
			jsonWriter.value(o.toString());
		}

		@Override
		public String read(JsonReader reader) throws IOException {
			if (reader.peek() == JsonToken.NULL) {
				reader.nextNull();
				return "";
			}
			return reader.nextString();
		}
	};

	// 自定义Integer适配器
	private static final TypeAdapter<?> INTEGER = new TypeAdapter() {
		@Override
		public void write(JsonWriter jsonWriter, Object o) throws IOException {
			if (o == null) {
				// 在这里处理null改为0
				jsonWriter.value(0);
				return;
			}
			jsonWriter.value(Integer.valueOf(o.toString()));
		}

		@Override
		public Integer read(JsonReader reader) throws IOException {
			if (reader.peek() == JsonToken.NULL) {
				reader.nextNull();
				return 0;
			}
			return reader.nextInt();
		}
	};
}
